package com.springboot.web;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * @Author: TongRui乀
 * @Date: 2019/3/11 13:49
 * @description：
 */
@RestController
@Slf4j
public class EsApiController {

    @Autowired
    private TransportClient transportClient;


    /**
     *  创建索引
     * @param indexName
     * @return
     */
    @GetMapping("createIndex/{indexName}")
    public String create01(@PathVariable String indexName){

        Settings.Builder settings = Settings.builder()
                .put("index.number_of_shards", 1)
                .put("index.number_of_replicas", 1);

        this.transportClient.admin().indices().prepareCreate(indexName).setSettings(settings).get();


        return "success";
    }


    @PutMapping("addMapping/{indexName}/{typeName}")
    public String addMapping(@PathVariable String indexName, @PathVariable String typeName) throws Exception {

        // 1设置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject(typeName)
                .startObject("properties")
                .startObject("name")
                .field("type", "text")
                .endObject()
                .startObject("score")
                .field("type", "text")
                .endObject()
                .startObject("des")
                .field("type", "text")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        // 2 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest(indexName).type(typeName).source(builder);

        this.transportClient.admin().indices().putMapping(mapping).get();


        return "success";
    }



    /**
     *  删除索引
     * @param indexName
     * @return
     */
    @GetMapping("deleteIndex/{indexName}")
    public String deleteIndex(@PathVariable String indexName){

        DeleteIndexResponse response = this.transportClient.admin().indices().prepareDelete(indexName).get();

        return "success";
    }


    /**
     *  添加数据
     * @param indexName
     * @param type
     * @param id
     * @param name
     * @param score
     * @return
     * @throws IOException
     */
    @PostMapping("addSource/{type}/{indexName}")
    public String addSource(@PathVariable String indexName,
                            @PathVariable String type,
                            @RequestParam(name = "des") String des,
                            @RequestParam(name = "name") String name,
                            @RequestParam(name = "score") Integer score) throws IOException {


        XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
                .field("name", name)
                .field("score", score)
                .field("des", des)
                .endObject();

        log.info(builder.string());

        this.transportClient.prepareIndex(indexName, type).setSource(builder).execute().actionGet();

        return "success";
    }



    @PutMapping("update/{indexName}/{type}/{id}")
    public String update(@PathVariable String indexName,
                         @PathVariable String type,
                         @PathVariable String id,
                         @RequestParam(name = "name") String name,
                         @RequestParam(name = "score") Integer score) throws IOException, ExecutionException, InterruptedException {

        UpdateRequest updateRequest = new UpdateRequest();

        updateRequest.index(indexName).type(type).id(id);

        updateRequest.doc(XContentFactory.jsonBuilder()
                                            .startObject()
                                            .field("name", name)
                                            .field("score", score)
                                            .endObject());

        this.transportClient.update(updateRequest).get();

        return "success";
    }

    @DeleteMapping("delete/{indexName}/{type}/{id}")
    public String delete(@PathVariable String indexName,
                         @PathVariable String type,
                         @PathVariable String id) throws ExecutionException, InterruptedException {

        DeleteRequest deleteRequest = new DeleteRequest();

        deleteRequest.index(indexName).type(type).id(id);

        this.transportClient.delete(deleteRequest).get();

        return "success";
    }

}
